package naga.x.db.impl;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

import naga.x.db.DBSession;
import naga.x.db.DBSessionListener;

public class SqlSession implements DBSession {
	
	protected int id;
	protected org.apache.ibatis.session.SqlSession session;
	protected DBSessionListener listener;
	
	protected static final AtomicInteger ID = new AtomicInteger();
	
	public SqlSession(org.apache.ibatis.session.SqlSession session) {
		this(session, null);
	}
	
	public SqlSession(org.apache.ibatis.session.SqlSession session, DBSessionListener listener) {
		this.session = Objects.requireNonNull(session);
		this.id = ID.incrementAndGet();
		this.listener = listener;
		if (listener != null) {
			listener.sessionOpened(this);
		}
	}

	@Override
	public <T> T getMapper(Class<T> type) {
		return session.getMapper(type);
	}

	@Override
	public void commit() {
		session.commit();
	}

	@Override
	public void rollback() {
		session.rollback();
	}

	@Override
	public void close() {
		session.close();
		if (listener != null) {
			listener.sessionClosed(this);
		}
	}

	@Override
	public int getId() {
		return this.id;
	}

	@Override
	public <E> List<E> selectList(String statement, Object parameter) {
		return session.selectList(statement, parameter);
	}

	@Override
	public int insert(String statement, Object parameter) {
		return session.insert(statement, parameter);
	}

	@Override
	public int update(String statement, Object parameter) {
		return session.update(statement, parameter);
	}

	@Override
	public int delete(String statement, Object parameter) {
		return session.delete(statement, parameter);
	}
	
//	public org.apache.ibatis.session.SqlSession session() {
//		return session;
//	}

}
